import React, { useRef, useState } from 'react';
import { PageContainer, ProForm, ModalForm,
  ProFormText, } from '@ant-design/pro-components';
import { FormInstance, message } from 'antd';
import { menulist, menuUpdate, menuAdd, menuDel } from '@/services/user'
import { Menu, Row, Col, Button, Spin, Cascader, Popconfirm } from 'antd';
import { useRequest, useUpdateEffect } from 'ahooks';

function AddButton({
  title,
  url,
  onAdd,
  onUpdate,
  onDel
}: {
  title: string,
  url: string,
  onAdd?: () => void,
  onUpdate?: () => void,
  onDel?: () => void,
}) {
  return <Row justify='space-between' align='middle' wrap={false}>
    <Col
      style={{
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        paddingRight: 15
      }}
    >
      {title}
    </Col>
    <Col>
      {url}
    </Col>
    <Col>
      {onAdd && <Button
        type="link"
        onClick={() => {
          onAdd()
        }}>新增子菜单</Button>}
      {onUpdate && <Button

        type="link"
        onClick={() => {
          onUpdate()
        }}>修改</Button>}
      {onDel && <Popconfirm
        title="确认删除？"
        key='3'
        onConfirm={() => {
          onDel()
        }}
        onCancel={() => { }}
        okText="确定"
        cancelText="取消"
      >
        <Button danger type="link">删除</Button>
      </Popconfirm>
      }
    </Col>
  </Row>
}
const TableList: React.FC = () => {
  const formRef = useRef<FormInstance>()
  const { SubMenu } = Menu
  const [defaultOpenKeys, setDefaultOpenKeys] = useState<any[]>(['0'])
  /**
   * 获取菜单
   */
  function MenuData(list: any[], keyPath: any[]): any[] {
    const newList = list.map((node) => {
      const newkeyPath = [...keyPath, node.key]
      if (node.children?.length) {
        return <SubMenu
          key={node.key}
          title={<AddButton
            title={node.value}
            url={node.url}
            onAdd={() => {
              setRow({
                level: newkeyPath
              })
              setVisible(true)
            }}
            onUpdate={node.key == 'treeNode' ? undefined : () => {
              setRow({
                id: node.key,
                name: node.value,
                url: node.url,
                level: keyPath
              })
              setVisible(true)
            }}
            onDel={node.key == 'treeNode' ? undefined : () => {
              doDel({ id: node.key })
            }}
          />}
        >
          {MenuData(node.children, newkeyPath)}
        </SubMenu>
      } else {
        return <Menu.Item key={node.key}>
          <AddButton
            title={node.value}
            url={node.url}
            onAdd={() => {
              setRow({
                level: newkeyPath
              })
              setVisible(true)
            }}
            onUpdate={() => {
              setRow({
                id: node.key,
                name: node.value,
                url: node.url,
                level: keyPath
              })
              setVisible(true)
            }}
            onDel={() => {
              doDel({ id: node.key })
            }}
          />
        </Menu.Item>
      }
    })
    return newList
  }
  function updateTreeData(list: any[]): any[] {
    const treeList: any[] = list.map((node) => {
      const list = updateTreeData(node.children)
      setDefaultOpenKeys((p) => [...new Set(p.concat(list, [node.key]))])
      return node.key
    })
    return treeList
  }
  function updateSelectData(list: any[]): any[] {
    const treeList: any[] = list.map((node) => ({
      value: node.key,
      label: node.value,
      children: updateSelectData(node.children),
    }))
    return treeList
  }
  const [options, setOptions] = useState<any[]>([])
  const [treeData, settreeData] = useState([])
  const {  loading, refresh } = useRequest(menulist, {
    onSuccess: (res) => {
      const list = [{ ...res[0]?.treeNode, key: 'treeNode' }] ?? []
      updateTreeData(list)
      setOptions(updateSelectData(list))
      settreeData(list)
    }
  })
  const [row, setRow] = useState<any>()
  const [visible, setVisible] = useState(false)
  /**
   * 删除菜单
   */
  const { run: doDel } = useRequest(menuDel, {
    manual: true,
    onSuccess: () => {
      refresh()
      message.success('删除成功')
    }
  })
  /**
   * 更新菜单
   */
  const { run: doUpdate } = useRequest(menuUpdate, {
    manual: true,
    onSuccess: () => {
      refresh()
      message.success('更新成功')
    }
  })
  /**
   * 新增菜单
   */
  const { run: doAdd } = useRequest(menuAdd, {
    manual: true,
    onSuccess: () => {
      refresh()
      message.success('新增成功')
    }
  })
  return (
    <PageContainer header={{breadcrumb: {}}} className='addMenu'>
      <Spin spinning={loading}>
        <Menu
          style={{ width: '100%' }}
          mode="inline"
          openKeys={defaultOpenKeys}
          selectable={false}
          expandIcon={<></>}
        >
          {MenuData(treeData, [])}
        </Menu>
      </Spin>
      <ModalForm
        title="新建表单"
        formRef={formRef}
        width={450}
        visible={visible}
        onVisibleChange={(visible) => {
          setVisible(visible)
        }}
        modalProps={{
          destroyOnClose: true
        }}
        onFinish={async (values) => {
          if (values.id) {
            await doUpdate(values)
          } else {
            await doAdd(values)
          }
          return true;
        }}
        initialValues={row}
      >
        <ProFormText
          name="id"
          hidden
        />
        <ProForm.Item
          label='所属位置'
          name='level'
          transform={(values) => ({
            levelOne: values[0] == 'treeNode' ? '1' : values[0],
            levelTwo: values[1],
            levelThree: values[2],
          })}
        >
          <Cascader
            disabled={row?.id}
            options={options}
            changeOnSelect
          />
        </ProForm.Item>
        <ProFormText
          width="md"
          name="name"
          label="菜单名称"
          placeholder="请输入名称"
        />
        <ProFormText
          width="md"
          name="url"
          label="菜单url"
          placeholder="请输入名称"
        />
      </ModalForm>
    </PageContainer>
  );
};

export default TableList;
